package com.zhongketech.sunflower.filter;

import com.zhongketech.sunflower.database.MessageItem;
import com.zhongketech.sunflower.database.SMS;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;


public class SmsService extends Service
{
	public static final String TAG = "BootService";

	private ContentObserver mObserver;

	@Override
	public void onCreate()
	{
		super.onCreate();
		Log.i(TAG, "onCreate().");
		addSMSObserver();
	}

	public void addSMSObserver()
	{
		Log.i(TAG, "add a SMS observer. ");
		ContentResolver resolver = getContentResolver();
		Handler handler = new SMSHandler(this);
		mObserver = new SMSObserver(resolver, handler);
		resolver.registerContentObserver(SMS.CONTENT_URI, true, mObserver);
	}

	@Override
	public IBinder onBind(Intent intent)
	{
		return null;
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		Log.i(TAG, "onDestroy().");
		this.getContentResolver().unregisterContentObserver(mObserver);

		//		Process.killProcess(Process.myPid());
		//		System.exit(0);
	}

	@SuppressLint("HandlerLeak")
	public class SMSHandler extends Handler
	{

		public static final String TAG = "SMSHandler";

		private Context mContext;

		public SMSHandler(Context context)
		{
			super();
			this.mContext = context;
		}

		public void handleMessage(Message message)
		{
			Log.i(TAG,  "handleMessage: " + message);
			MessageItem item = (MessageItem) message.obj;
			//delete the sms
			Uri uri = ContentUris.withAppendedId(SMS.CONTENT_URI, item.getId());
			mContext.getContentResolver().delete(uri, null, null);
			Log.i(TAG,  "delete sms item: " + item);
			
			Toast.makeText(getApplicationContext(), "禁止发送短信",
					Toast.LENGTH_SHORT).show();

		}

	}

}